using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace ChatBackend.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class FileController : ControllerBase
    {
        private readonly IWebHostEnvironment _environment;
        private readonly ILogger<FileController> _logger;

        public FileController(IWebHostEnvironment environment, ILogger<FileController> logger)
        {
            _environment = environment;
            _logger = logger;
        }

        [HttpPost("upload-avatar")]
        public async Task<ActionResult<UploadResult>> UploadAvatar(IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest(new { message = "请选择要上传的文件" });
                }

                // 验证文件类型
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".webp" };
                var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                
                if (!allowedExtensions.Contains(fileExtension))
                {
                    return BadRequest(new { message = "只支持 JPG、PNG、GIF、WebP 格式的图片" });
                }

                // 验证文件大小 (5MB)
                if (file.Length > 5 * 1024 * 1024)
                {
                    return BadRequest(new { message = "文件大小不能超过 5MB" });
                }

                // 获取用户ID
                var userId = GetUserId();
                if (!userId.HasValue)
                {
                    return Unauthorized();
                }

                // 创建上传目录
                var webRootPath = _environment.WebRootPath ?? Path.Combine(_environment.ContentRootPath, "wwwroot");
                var uploadsDir = Path.Combine(webRootPath, "uploads", "avatars");
                if (!Directory.Exists(uploadsDir))
                {
                    Directory.CreateDirectory(uploadsDir);
                }

                // 生成唯一文件名
                var fileName = $"{userId}_{DateTime.UtcNow:yyyyMMddHHmmss}{fileExtension}";
                var filePath = Path.Combine(uploadsDir, fileName);

                // 删除用户之前的头像文件
                await DeleteOldAvatarFiles(userId.Value, uploadsDir);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 返回文件URL
                var fileUrl = $"/uploads/avatars/{fileName}";
                
                return Ok(new UploadResult
                {
                    Url = fileUrl,
                    FileName = fileName,
                    Size = file.Length
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "上传头像失败");
                return StatusCode(500, new { message = "上传失败", error = ex.Message });
            }
        }

        private async Task DeleteOldAvatarFiles(int userId, string uploadsDir)
        {
            try
            {
                var files = Directory.GetFiles(uploadsDir, $"{userId}_*");
                foreach (var file in files)
                {
                    System.IO.File.Delete(file);
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "删除旧头像文件失败，用户ID: {UserId}", userId);
            }
        }

        private int? GetUserId()
        {
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            return int.TryParse(userIdClaim, out var userId) ? userId : null;
        }
    }

    public class UploadResult
    {
        public string Url { get; set; } = string.Empty;
        public string FileName { get; set; } = string.Empty;
        public long Size { get; set; }
    }
}
